package com.itheima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.admin.feign.AdChannelFeign;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.service.ApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.nio.channels.Channel;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ApiServiceImpl implements ApiService {

    @Autowired
    private AdChannelFeign adChannelFeign;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 远程调用admin微服
     * 查询所有频道列表
     * <p>
     * 使用redis缓存
     *
     * @return
     */
    @Override
    public List<AdChannel> getChannelList() {
        //1. 先从redis 中查
        String channelListString = stringRedisTemplate.opsForValue().get(SystemConstants.REDISKEY_CHANNELLIST);
        List<AdChannel> channelList = new ArrayList<>();
        if(StringUtils.isNotEmpty(channelListString)){
            // 有数据
            channelList = JSON.parseArray(channelListString, AdChannel.class);
        }

        if(CollectionUtils.isEmpty(channelList)){
            log.info("远程调用Admin微服查询频道列表...");
            //2. 如果没数据才从admin微服务
            ResultVo<List<AdChannel>> resultVo = adChannelFeign.listAll();
            if(!resultVo.isSuccess()){
                throw new LeadNewsException("远程调用查询频道列表失败");
            }
            //3. 查询到后存入redis
            channelList = resultVo.getData();
            stringRedisTemplate.opsForValue().set(SystemConstants.REDISKEY_CHANNELLIST, JSON.toJSONString(channelList));
        }
        return channelList;
    }
}
